package com.example.myexample;

import java.io.IOException;
import java.util.List;

import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.OnZoomChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ZoomControls;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends Activity implements SurfaceHolder.Callback {

	SurfaceView cameraView;
	SurfaceHolder holder;
	Camera camera;
	
	int numberOfCameras = 0;
	int frontBackCameraID = 0;
	
	// Overlay controls
	Overlay grid;
	ImageView gridControl;
	ImageView capture;
	ZoomControls zoomControl;
	int currentZoomLevel = 0;
	int maxZoomLevel = 0;
	boolean isZooming = false;
	
	// control variable
	boolean isShowGrid = false;
	
	// Image sizes
	List<Camera.Size> pictureSizes;
	List<Camera.Size> previewSizes;
	
	FrameLayout mainlayout;
	
	Camera.ShutterCallback shuttercb = new Camera.ShutterCallback() {
		
		@Override
		public void onShutter() {
			// TODO Auto-generated method stub
			Log.i("SUMPRO","Take picture");
		}
	};
	
	Camera.PictureCallback rawCallBack = new Camera.PictureCallback() {
		
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			// TODO Auto-generated method stub
			
		}
	};
	
	Camera.PictureCallback jpegCallBack = new Camera.PictureCallback() {
		
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			// TODO Auto-generated method stub
			
		}
	};
	
	@SuppressLint("InlinedApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.camerapreview);
		
		getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LOW_PROFILE );
		
		mainlayout = (FrameLayout)findViewById(R.layout.camerapreview);
		zoomControl = (ZoomControls)findViewById(R.id.zoomControl);
		grid = (Overlay)findViewById(R.id.grid);
		gridControl = (ImageView)findViewById(R.id.gridControl);
		gridControl.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				isShowGrid = !isShowGrid;
				grid.setIsShowGrid(isShowGrid);
				Log.i("SUMPRO", "isShowGrid:" + isShowGrid);
				grid.invalidate();
			}
		});
		capture = (ImageView) findViewById(R.id.capture);
		capture.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.i("SUMPRO", "capture:");
			}
		});
		
		cameraView = (SurfaceView)findViewById(R.id.cameraPreview);
		holder = cameraView.getHolder();
		holder.addCallback(this);
		camera = Camera.open();
		
		// Find the total number of cameras available
        numberOfCameras = Camera.getNumberOfCameras();

        // Find the ID of the default camera
        CameraInfo cameraInfo = new CameraInfo();
            for (int i = 0; i < numberOfCameras; i++) {
                Camera.getCameraInfo(i, cameraInfo);
                if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
                	frontBackCameraID = i;
                }
            }
		
		Camera.Parameters parameters = camera.getParameters();
		if(parameters.isZoomSupported()) {
			maxZoomLevel = parameters.getMaxZoom();
			Log.i("SUMPRO", "maxZoomLevel:" + maxZoomLevel);
			zoomControl.setIsZoomInEnabled(true);
			zoomControl.setIsZoomOutEnabled(true);
			camera.setZoomChangeListener(new OnZoomChangeListener() {
				
				@Override
				public void onZoomChange(int zoomValue, boolean stopped, Camera camera) {
					// TODO Auto-generated method stub
					if(stopped)
						isZooming = false;
				}
			});
			
			zoomControl.setOnZoomInClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(currentZoomLevel < maxZoomLevel && !isZooming){
                        currentZoomLevel += 10 ;
                        isZooming = true;
                        camera.startSmoothZoom(currentZoomLevel);
                    }
				}
			});
			
			zoomControl.setOnZoomOutClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(currentZoomLevel > 0 && !isZooming){
                        currentZoomLevel -= 10;
                        isZooming = true;
                        camera.startSmoothZoom(currentZoomLevel);
                    }
				}
			});
		}
		
		// get support size
		previewSizes = parameters.getSupportedPreviewSizes();
		for(int i = 0; i < previewSizes.size();i++) {
			Log.i("SUMPRO", "Width:" + previewSizes.get(i).width + " - height:" + previewSizes.get(i).height);
		}
		Log.i("SUMPRO", "picture size");
		pictureSizes = parameters.getSupportedPictureSizes();
		for(int i = 0; i < previewSizes.size();i++) {
			Log.i("SUMPRO", "Width:" + previewSizes.get(i).width + " - height:" + previewSizes.get(i).height);
		}
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onConfigurationChanged(android.content.res.Configuration)
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		//onOrientationChanged(newConfig.orientation)
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		setCameraDisplayOrientation(this, frontBackCameraID, camera);
        camera.startPreview();
	}

	public static void setCameraDisplayOrientation(Activity activity,
	         int cameraId, android.hardware.Camera camera) {
	     android.hardware.Camera.CameraInfo info =
	             new android.hardware.Camera.CameraInfo();
	     android.hardware.Camera.getCameraInfo(cameraId, info);
	     int rotation = activity.getWindowManager().getDefaultDisplay()
	             .getRotation();
	     int degrees = 0;
	     switch (rotation) {
	         case Surface.ROTATION_0: degrees = 0; break;
	         case Surface.ROTATION_90: degrees = 90; break;
	         case Surface.ROTATION_180: degrees = 180; break;
	         case Surface.ROTATION_270: degrees = 270; break;
	     }

	     int result;
	     if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
	         result = (info.orientation + degrees) % 360;
	         result = (360 - result) % 360;  // compensate the mirror
	     } else {  // back-facing
	         result = (info.orientation - degrees + 360) % 360;
	     }
	     camera.setDisplayOrientation(result);
	 }

	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if(camera != null) {
			try {
				camera.setPreviewDisplay(holder);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		if (camera != null) {
			camera.stopPreview();
        }
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (camera != null) {
            camera.release();
            camera = null;
        }
	}

	public void onOrientationChanged(int orientation) {
	     android.hardware.Camera.CameraInfo info =
	            new android.hardware.Camera.CameraInfo();
	     android.hardware.Camera.getCameraInfo(frontBackCameraID, info);
	     orientation = (orientation + 45) / 90 * 90;
	     int rotation = 0;
	     if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
	         rotation = (info.orientation - orientation + 360) % 360;
	     } else {  // back-facing camera
	         rotation = (info.orientation + orientation) % 360;
	     }
	     Camera.Parameters parameters = camera.getParameters();
	     parameters.setRotation(rotation);
	 }

	
}
